package com.jk;

/**
 * 关于懒汉式的线程安全问题，使用同步机制
 * 对于一般的方法内，使用同步代码块，可以考虑使用this
 * 对于静态方法而言，使用当前类本身充当锁
 */
public class Singleton1 {
    private Singleton1() {

    }

    private static Singleton1 instance = null;

    public static Singleton1 getInstance() {
        if (instance == null) {
            synchronized (Singleton1.class) {
                if (instance == null) {
                    instance = new Singleton1();
                }
            }
        }
        return instance;
    }
}

class Test1{
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {

            public void run() {
                int i = Singleton1.getInstance().hashCode();
                System.out.println(i + "------" + Thread.currentThread().getName());
            }
        };

        Thread th1 = new Thread(runnable);
        Thread th2 = new Thread(runnable);
        th1.start();
        th2.start();
    }
}
